<template>
  <el-main style="padding: 0px 20px">
    <el-row style="margin:20px 0px">
      <!-- <el-col :span="2"> -->
        <el-button style="float:left;margin-right:10px" icon="el-icon-plus" v-if="hasPerm('sys:role:add')" type="success" size="medium" @click="addRole">新增</el-button>
      <!-- </el-col> -->
      <my-Search :searchWay="true" :inputPlaceholder="'角色名称'" @onSearch="getSearchContent"></my-Search>
    </el-row>

    <el-table
      :height="tableHeight"
      :data="roleList"
      border
      stripe
      row-key="id"
      :expand-row-keys="roleList"
      :tree-props="{ children: 'children' }"
    >
      <el-table-column type="expand" width="55">
        <template slot-scope="treeData">
          <el-row type="flex" justify="center" align="middle" v-show="treeData.row.menuList==''">
              <el-col :span="2">暂无权限</el-col>
          </el-row>
          <el-row
              type="flex"
              justify="center"
              align="middle"
              class="tableRow1"
              v-for="firstRole in treeData.row.menuList"
              :key="firstRole.value"
          >
            <el-col :span="4" :offset="1">
              <el-tag effect="dark" type="danger" size="small"> {{firstRole.label}} </el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <el-col :span="19">
              <el-row
                type="flex"
                align="middle"
                class="tableRow2"
                v-for="secondRole in firstRole.children"
                :key="secondRole.value"
              >
                <el-col :span="4" :offset="1">
                  <el-tag effect="dark" type="success" size="small"> {{secondRole.label}} </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="13" :offset="1">
                  <el-tag
                    effect="dark"
                    size="small"
                    v-for="thirdRole in secondRole.children"
                    :key="thirdRole.value"
                    >
                      {{thirdRole.label}}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>

      <el-table-column width="200px" prop="roleName" align="center" label="角色名称"></el-table-column>
      <el-table-column width="150px" prop="roleCode" align="center" label="角色代码"></el-table-column>
      <el-table-column prop="remark" align="center" label="角色介绍"></el-table-column>
      <el-table-column width="200px" prop="updateTime" align="center" label="修改时间"></el-table-column>
      <el-table-column width="200px" prop="createTime" align="center" label="创建时间"></el-table-column>
      <el-table-column width="120px" prop="status" align="center" label="状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="editRoleStatus(scope.row.id)"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column align="center"  label="操作">
        <template slot-scope="scope">
          <el-button v-if="hasPerm('sys:role:rolemenu')" type="warning" icon="el-icon-set-up" size="small" @click="openRoleMenu(scope.row)">分配权限</el-button>
          <el-button v-if="hasPerm('sys:role:edit')" type="primary" icon="el-icon-edit" size="small" @click="editRole(scope.row)">编辑</el-button>
          <el-button v-if="hasPerm('sys:role:delete')" type="danger" icon="el-icon-delete" size="small" @click="deleteRole(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区 -->
    <pagination
    ref="pagination"
    @pagination="getPagination"
    :total="parseInt(totalPage)"
    :page="parseInt(searchCondition.page)"
    :limit="parseInt(searchCondition.pageSize)"
    :pageSizes="paginationSize"
    ></pagination>

    <!-- 新增或编辑弹框 -->
    <my-dialog
      :title="roleDialog.title"
      :width="roleDialog.width"
      :height="roleDialog.height"
      :visible="roleDialog.visible"
      @onClose="onClose"
      @onConfirm="onConfirm"
    >
      <div slot="content">
        <el-form
          :model="roleFormData"
          ref="roleFormRef"
          :rules="rules"
          label-width="80px"
          size="small"
        >

          <el-form-item prop="roleName" size="small" label="角色名称">
            <el-input v-model="roleFormData.roleName"></el-input>
          </el-form-item>
          <el-form-item prop="roleCode" size="small" label="角色代码">
            <el-input v-model="roleFormData.roleCode"></el-input>
          </el-form-item>
          <el-form-item prop="remark" size="small" label="角色介绍">
            <el-input
              type="textarea"
              maxlength="50"
              show-word-limit
              v-model="roleFormData.remark"
              :rows="3"
              resize="none"
              placeholder="（限50字）"
            ></el-input>
          </el-form-item>

        </el-form>
      </div>
    </my-dialog>

    <!-- 分配权限抽屉 -->
    <el-drawer
      :title="roleMenuDrawer.title"
      :visible.sync="roleMenuDrawer.visible"
      :direction="roleMenuDrawer.direction"
      :size="roleMenuDrawer.size"
      :before-close="onRoleMenuClose"
      >
        <div class="drawer-body">
          <div class="drawer-header">
            <el-input clearable placeholder="输入权限名称快速查找" v-model="roleMenuFilterText"> </el-input>
          </div>
          <div class="drawer-main">
              <el-tree
                :filter-node-method="filterNode"
                ref="roleMenuTree"
                :data="roleMenuData"
                node-key="id"
                :props="defaultProps"
                empty-text="暂无数据"
                :show-checkbox="true"
                :highlight-current="true"
                default-expand-all
              />
          </div>
          <div class="drawer-footer">
            <el-button @click="onRoleMenuClose">取 消</el-button>
            <el-button @click="onRoleMenuConfirm" type="primary" >保 存</el-button>
          </div>
        </div>
    </el-drawer>
  </el-main>
</template>

<script>
import {
  getRoleListApi,
  addRoleApi,
  editRoleApi,
  editRoleStatusApi,
  deleteRoleApi,
  getRoleMenuApi,
  editRoleMenuApi,
  getRoleMenuTreeApi
} from "@/api/role";
import myDialog from "@/components/MyDialog/index";
import mySearch from "@/components/MySearch/index";
import pagination from "@/components/Pagination/index";
import leafUtils from "@/utils/leafUtils";
export default {
  components: { myDialog, mySearch,pagination },
  data() {
    return {
      //新增或编辑表单验证规则
      rules: {
        roleName: [{ required: true, trigger: "blur", message: "请填写角色名称" }],
        roleCode: [{ required: true, trigger: "blur", message: "请填写角色代码" }]
      },
      //true：编辑 flase :新增
      actionType: "",
      //新增或编辑表单数据域
      roleFormData: {
        id: "",
        roleName: "",
        roleCode: "",
        remark: "",
        status: "",
        version:""
      },
      //新增或编辑弹框属性
      roleDialog: {
        title: "",
        width: 520,
        height: 200,
        visible: false,
      },
      //分配权限的抽屉
      roleMenuDrawer: {
        title: "",
        direction: "rtl",
        size: "20%",
        visible: false,
      },
      //表格高度
      tableHeight: 0,
      //角色数量列表
      roleList: [],
      //查询条件
      searchCondition :{
        page: 1,
        pageSize: 10,
        searchContent: ""
      },
      //分页容量
      paginationSize: [1, 3, 5, 10],
      //查询返回 总记录数
      totalPage: 0,

      //树属性配置
      defaultProps: {
        children: "children",
        label: "label",
      },
      //分配权限树数据域
      roleMenuData: [],
      //角色id
      roleId: "",
      roleMenuFilterText: "",
    };
  },
  created() {
    this.getRoleList();
  },
  mounted() {
    this.$nextTick(() => {
      //有页码区就高度多-120
      this.tableHeight = window.innerHeight - 170 - 120;
    })
  },
  methods: {
    //获取角色列表
    async getRoleList() {
      let res = await getRoleListApi(this.searchCondition);
      if (res && res.code == 200) {
        this.totalPage = res.data.total;
        let copyList = res.data.records;
        copyList.forEach( item => {
          this.getRoleMenuTree(item.id).then((res)=>{
            item.menuList = res
          })
        })
        this.roleList = copyList;
      }
    },
    //获取角色权限列表
    async getRoleMenuTree(id){
      let rid = parseInt(id)
      let parm = {
        rid : rid,
      };
      let res = await getRoleMenuTreeApi(parm);
      if(res.code==200) {
        return res.data;
      }
    },
    //内容查询
    getSearchContent(val){
      this.searchCondition.searchContent = val;
      this.getRoleList();
    },
    //分页查询
    getPagination(val){
      this.searchCondition.page = val.page;
      this.searchCondition.pageSize = val.limit;
      this.getRoleList();
    },
    //修改状态
    async editRoleStatus(value){
        let res = await editRoleStatusApi(value);
        if (res && res.code == 200) {
          //刷新列表
          this.getRoleList();
          this.$message.success(res.msg);
        }
    },
    //新增或编辑确认
    onConfirm() {
      this.$refs.roleFormRef.validate(async (valid) => {
        if (valid) {
          let res = null;
          if (this.actionType) {
            //编辑
            res = await editRoleApi(this.roleFormData);
          } else {
            //新增
            res = await addRoleApi(this.roleFormData);
          }
          if (res && res.code == 200) {
            //刷新列表
            this.getRoleList();
            this.roleDialog.visible = false;
            this.$message.success(res.msg);
          }
        }
      });
    },
    //新增或编辑取消
    onClose() {
      this.roleDialog.visible = false;
    },
    //新增按钮
    addRole() {
      this.$resetForm("roleFormRef", this.roleFormData);
      this.roleDialog.title = "新增角色";
      this.roleDialog.visible = true;
      this.actionType = false;
    },
    //编辑按钮
    editRole(row) {
      this.$resetForm("roleFormRef", this.roleFormData);
      //把当前要编辑的数据复制到数据域，tApi给表单回显
      this.$objCoppy(row, this.roleFormData);
      //设置编辑的标识
      this.actionType = true;
      //设置弹框属性
      this.roleDialog.title = "编辑角色";
      this.roleDialog.visible = true;
    },
    //删除按钮
    async deleteRole(row) {
      let confirm = await this.$myconfirm("确定删除【"+row.roleName+"】角色吗？");
      if (confirm) {
        let parm = {
          id: row.id
        };
        let res = await deleteRoleApi(parm);
        if (res && res.code == 200) {
          // 检查最后一页是否只有一条数据
          if(this.searchCondition.pageSize ==1 || this.totalPage % this.searchCondition.pageSize ==1){
            this.searchCondition.page-=1;
          }
          //刷新列表
          this.getRoleList();
          this.$message.success(res.msg);
        }
      }
    },
    //打开抽屉
    openRoleMenu(row){
      this.getRoleMenu(row);
      this.roleMenuDrawer.title = "为【" + row.roleName + "】分配权限";
      this.roleMenuDrawer.visible = true;
    },
    //查询权限树
    async getRoleMenu(row){
      let that = this;
      this.roleId = row.id;
      let parm = {
        uid: this.$store.getters.userId,
        rid: row.id,
      };
      let res = await getRoleMenuApi(parm);
      if (res && res.code == 200) {
        //当前登录用户所拥有的所有权限
        let menuList = res.data.roleMenuList;
        //当前被分配的角色所拥有的权限
        let selectIds = res.data.checkList;
        //判断是否是末级
        let { setLeaf } = leafUtils();
        let newMenuList = setLeaf(menuList);
        this.setDisabled(newMenuList)
        this.roleMenuData = newMenuList;
        this.$nextTick(() => {
          let nodes = that.$refs.roleMenuTree.children;
          that.setChild(nodes, selectIds, that);
        });
      }
    },
    //遍历查看被禁用的权限
    setDisabled(list){
      list.forEach(item =>{
        if(item.status==0){ item.disabled = true;}
        if(item.children.length>0){ this.setDisabled(item.children) }
      })
    },
    //遍历设置子节点
    setChild(childNodes, selectIds, that) {
      if (childNodes && childNodes.length > 0) {
        {
          for (let j = 0; j < childNodes.length; j++) {
            var node = that.$refs.roleMenuTree.getNode(childNodes[j]);
            if (selectIds && selectIds.length > 0) {
              for (let h = 0; h < selectIds.length; h++) {
                if (selectIds[h] == childNodes[j].id) {
                  if (childNodes[j].open) {
                    that.$refs.roleMenuTree.setChecked(node, true);
                    break;
                  }
                }
              }
            }
            if (childNodes[j].children) {
              that.setChild(childNodes[j].children, selectIds, that);
            }
          }
        }
      }
    },
    //过滤查询权限
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    //更新权限
    async onRoleMenuConfirm(){
      let listId = this.$refs.roleMenuTree
        .getCheckedKeys()
        .concat(this.$refs.roleMenuTree.getHalfCheckedKeys());
      let parm = {
        rid: this.roleId,
        midList: listId,
      };
      let res = await editRoleMenuApi(parm);
      if (res && res.code == 200) {
        this.roleMenuDrawer.visible = false;
        this.$message.success(res.msg);
      }
    },
    //关闭抽屉
    onRoleMenuClose(){
      this.roleMenuData = [];
      this.roleMenuFilterText = '';
      this.roleMenuDrawer.visible = false;
    }
  },
  watch: {
    roleMenuFilterText(val) {
      this.$refs.roleMenuTree.filter(val);
    }
  }
};
</script>

<style lang="scss" scoped>
 .drawer-body{
  height: 100vh;
  padding: 0 20px 10px 20px;
  .drawer-header{
    height: 70px;
    line-height: 70px;
    width: 80%;
  }
  .drawer-main{
    min-height: calc(100vh - 220px);
  }
  .drawer-footer{
    height: 50px;
    line-height: 50px;
    display: flex;
    button {
      flex: 1;
    }
  }
 }
  .el-tag{
      margin: 15px 1px;
  }
  .tableRow1{
      margin: 0 40px;
      border-bottom: solid 1px #2495e7;
  }
  .tableRow2{
      border-bottom: solid 1px #cbcbcb;
  }
  .tableRow1:last-child,.tableRow2:last-child{
      border: none;
  }
</style>
